<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Class Notify_model extends Teaboy_model{
	
		private $ttg = 5; //time to game
		private $channel = 'teaboy'; //public channel
		private $userChannel = 'teaboyUser'; //private channel
	
		public function __contruct(){
			parent::Controller();
			
		}
		
		
		public function sendPreWarning(){
			
			//send email to all users
			$this->warningEmail();
			
			//send a warning via socket?
			$this->sendSocketWarning();
			
		}
		
		public function sendCountdown($seconds){
			$oResult = $this->pusher->trigger($this->channel, 'countdown', array('message' => 'A new game is about to start', 'seconds'=>$seconds));
		}
		
		public function gameOver(){
			$this->pusher->trigger($this->channel, 'gameOver', array('result'=>'gameOver')); 
		}
		
		public function sendResults(){
			
			//get all winners
			$aWinners = $this->Result_model->getWinners();
			$aLoser = $this->Result_model->getLosers();
			//print_r($aLoser);
			
			//send winners;
			foreach($aWinners as $winner){
				$winnerId = $winner['id'];
				$this->pusher->trigger($this->userChannel.$winnerId, 'status', array('result'=>'winner', 'players'=>$aLoser['name']));
			}		
			
			//get loser ID
			$loserId = $aLoser['id'];
			$this->pusher->trigger($this->userChannel.$loserId, 'status', array('result'=>'loser', 'players'=>$aWinners));
			
			//$this->pusher->trigger($this->userChannel.'11', 'status', array('result'=>'winner', 'players'=>$aLoser['name']));
			//$this->pusher->trigger($this->channel, 'status', array('result'=>'loser', 'players'=>$aWinners));
		}
		
		public function gameStart(){
			//send a message with current game id
			$this->pusher->trigger($this->channel, 'start', array('gameId' => $this->getCurrentGame()));
		}
		
		private function warningEmail(){
			
			//get all registered users
			$aUsers = $this->Register_model->allUsers();
			$aTo = array();
			foreach($aUsers as $user){
				$aTo[] = $user['email'];
			}
			
			$message = "Hi,\n\nThis is the Teaboy here, just saying it's time for tea, so get logged onto your teaboy app\n\nThanks\n\nThe Teaboy";
			
			$this->load->library('email');

			$this->email->from('warning@teabody.com', 'The Teaboy');
			$this->email->to('warning"teaboy.com');
			$this->email->bcc($aTo); 
			
			$this->email->subject('Teaboy: '.$this->ttg.' minute warning');
			$this->email->message($message);	
			
			$oResult = $this->email->send();
			
		}
		
		public function sendSocketWarning(){
			$oResult = $this->pusher->trigger($this->channel, 'newGame', array('message' => 'A new game is about to start'));
 
		}

}